package comp302.prototype.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class XMLParser {
	private Scanner scanner;
	private String fileName;

	public XMLParser(String fileName) {

		try {
			scanner = new Scanner(new File(fileName));
			scanner.useDelimiter("[\n\t<?> ]+");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public XMLNode parseFile() {
		XMLNode node;

		if (scanner == null) {
			try {
				scanner = new Scanner(new File(fileName));
				scanner.useDelimiter("[\n\t<?> ]+");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return null;
			}
		}

		node = parseNode(null);
		scanner.close();
		return node;
	}

	private XMLNode parseNode(XMLNode currentNode) {
		XMLNode node = currentNode;

		while (scanner.hasNext()) {
			String str = scanner.next();

			if (str.equalsIgnoreCase("xml")) {
				str = scanner.next();
			}

			if (node == null && isTagString(str)) {
				node = new XMLNode(str);
			} else if (node != null && isAttributeString(str)) {
				node.setAttribute(attributeStringName(str),
						attributeStringValue(str));
			} else if (node != null && isTagString(str)) {
				node.addChild(parseNode(new XMLNode(str)));
			} else if (node != null && isCloseTagString(str)
					&& str.equalsIgnoreCase("/" + node.getName())) {
				return node;
			}
		}

		return node;
	}

	private boolean isAttributeString(String str) {
		return str.matches("[a-zA-Z0-9]+=\"-*[a-zA-Z0-9.]+\"");
	}

	private boolean isTagString(String str) {
		return str.matches("[a-zA-Z0-9]+");
	}

	private boolean isCloseTagString(String str) {
		return str.matches("/[a-zA-Z0-9]+");
	}

	private String attributeStringName(String str) {
		Scanner scnr = new Scanner(str);
		scnr.useDelimiter("[=\"]+");

		return scnr.next();
	}

	private String attributeStringValue(String str) {
		Scanner scnr = new Scanner(str);
		scnr.useDelimiter("[=\"]+");
		scnr.next();

		return scnr.next();
	}
}
